[assembly: WebActivator.PreApplicationStartMethod(typeof(MobileTrack.Web.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(MobileTrack.Web.NinjectWebCommon), "Stop")]

namespace MobileTrack.Web
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Web;
    using System.Web.Security;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    using MobileTrack.Core.Data;
    using MobileTrack.Web.Controllers;
    using Ninject;
    using Ninject.Web.Common;

    [ExcludeFromCodeCoverage]
    public static class NinjectWebCommon
    {
        private static readonly Bootstrapper Bootstrapper = new Bootstrapper();

        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            Bootstrapper.Initialize(CreateKernel);
        }

        public static void Stop()
        {
            Bootstrapper.ShutDown();
        }

        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }

        private static void RegisterServices(IKernel kernel)
        {
            // Db context.
            kernel.Bind<IRepositories>().ToMethod(ninjectContext => new MobileTrackRepositories(new MobileTrackContext(MobileTrackApplication.ConnectionStringName))).InRequestScope();

            // Membership provider
            kernel.Bind<MembershipProvider>().ToMethod(ninjectContext => Membership.Provider).InRequestScope();

            // Role provider
            kernel.Bind<RoleProvider>().ToMethod(ninjectContext => Roles.Provider).InRequestScope();

            // Controllers.
            kernel.Bind<AbonosController>().ToSelf();
            kernel.Bind<AccountController>().ToSelf();
            kernel.Bind<HomeController>().ToSelf();
            kernel.Bind<ImeisController>().ToSelf();
            kernel.Bind<SeguimientosController>().ToSelf();
        }
    }
}
